package com.qcu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qcu.dto.DoctorInfoDTO;
import com.qcu.entity.DoctorInfo;
import com.qcu.service.DoctorInfoService;
import com.qcu.service.MinioService;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @Name: MyComputer
 * @ClassName DoctorInfoController
 * @Description:
 * @date 2025/3/29 16:32
 */
@RestController
@RequestMapping("/admin/doctorInfo")
public class DoctorInfoController {

    @Resource
    private DoctorInfoService doctorInfoService;

    @Resource
    private MinioService minioService;

    /**
     * 自动获取所有的医生,当修改的时候自动保存医生信息；如果已经存在，则修改状态为 1（逻辑删除）
     * @param file 图片
     * @param doctorId 医生id
     * @param job 职位
     * @param title 头衔
     * @return
     */
    @PostMapping(consumes = "multipart/form-data")
    public Response save(@RequestPart(required = false) MultipartFile file , @RequestParam Integer doctorId, @RequestParam String job, @RequestParam String title , @RequestParam(required = false) Integer id) {
        try {
            boolean update = true;
            if (id != null){
                update = doctorInfoService.update(new LambdaUpdateWrapper<DoctorInfo>().set(DoctorInfo::getState, 1).eq(DoctorInfo::getId, id));
            }
            if (!update){
                return Response.failure(ResponseCode.FAILURE, "更新失败");
            }

            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String type = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String url = minioService.upload(originalFilename, bytes, type);

            DoctorInfo doctorInfo = new DoctorInfo();
            doctorInfo.setDoctorId(doctorId);
            doctorInfo.setPicture(url);
            doctorInfo.setJob(job);
            doctorInfo.setTitle(title);
            doctorInfoService.save(doctorInfo);
            return Response.success();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取医生信息
     * @param departmentId 部门id（非必须，管理员进行操作时不需要传）
     * @return
     */
    @GetMapping("/{departmentId}")
    public Response get(@PathVariable(required = false) Integer departmentId) {
        List<DoctorInfoDTO> list = doctorInfoService.getDoctors(departmentId);
        return Response.success(list);
    }

    @GetMapping()
    public Response get() {
        List<DoctorInfoDTO> list = doctorInfoService.getDoctors(null);
        return Response.success(list);
    }
}
